package org.ww.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.awt.print.Book;
import java.beans.PropertyVetoException;

/**
 * @Profile
 *   指定某个组件在特定得环境下注册到容器中，如果不指定，任何环境都能够注册到容器中
 *   1、加了该注解得某个bean，只有这个环境被激活得时候才能注册到容器中，默认是default
 *   2、写在配置类上时，只有是指定得环境下整个配置类才能生效
 *   3、没有标注环境标识得bean，在任何环境下都是加载得
 */
@Profile("dev")
@PropertySource("classpath:/dbconfig.properties")
@Configuration
public class MainDataSourceConfig implements EmbeddedValueResolverAware {

    @Value("db.user")
    private String user;
    private String driver;
    private StringValueResolver stringValueResolver;

    @Bean
    public Book book(){
        return new Book();
    }

    @Profile("dev")
    @Bean("DevDataSource")
    public DataSource dataSourceDev(@Value("db.pwd") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dev");
        dataSource.setDriverClass(driver);
        driver=stringValueResolver.resolveStringValue("${db.driver}");
        return dataSource;
    }
    @Profile("test")
    @Bean("TestDataSource")
    public DataSource dataSourceTest(@Value("db.pwd") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setDriverClass(driver);
        driver=stringValueResolver.resolveStringValue("${db.driver}");
        return dataSource;
    }
    @Profile("prod")
    @Bean("ProdDataSource")
    public DataSource dataSourceProd(@Value("db.pwd") String pwd) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(pwd);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/prod");
        dataSource.setDriverClass(driver);
        driver=stringValueResolver.resolveStringValue("${db.driver}");
        return dataSource;
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.stringValueResolver=resolver;
    }
}
